package com.beigai.imessage.message.queue;

import com.beigai.imessage.message.dto.MessageDTO;

import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xxl on 2017/5/17.
 */
public class MemoryPriorityQueue {
    private static Map<String, PriorityQueue<MessageDTO>> mQueue = new ConcurrentHashMap<String, PriorityQueue<MessageDTO>>();

    /**
     * 初始化聊天队列，每组对话，一个队列
     *
     * @param key
     * @return
     */
    private static PriorityQueue<MessageDTO> initQueue(String key) {
        PriorityQueue<MessageDTO> messageDTOS = mQueue.get(key);
        if (messageDTOS == null) {
            messageDTOS = new PriorityQueue<MessageDTO>();
            mQueue.put(key, messageDTOS);
        }
        return messageDTOS;
    }

    /**
     * 发送消息
     *
     * @param key
     * @param messageDTO
     */
    public static void sendMessage(String key, MessageDTO messageDTO) {
        PriorityQueue<MessageDTO> messageDTOS = initQueue(key);
        messageDTOS.add(messageDTO);
    }

    /**
     * 接收消息
     *
     * @param key
     * @return
     */
    public static MessageDTO receiveMessage(String key) {
        PriorityQueue<MessageDTO> messageDTOS = initQueue(key);
        MessageDTO messageDTO = messageDTOS.poll();
        return messageDTO;
    }

    /**
     * 销毁队列
     *
     * @param key
     */
    public static void destroy(String key) {
        PriorityQueue<MessageDTO> messageDTOS = mQueue.get(key);
        if (messageDTOS != null) {
            mQueue.remove(key);
        }
    }
}
